package com.example.quiz.service.impl;

import com.example.quiz.dao.QuestionMapper;
import com.example.quiz.dao.AnswerRecordMapper;
import com.example.quiz.dao.WrongQuestionMapper;
import com.example.quiz.model.Question;
import com.example.quiz.model.AnswerRecord;
import com.example.quiz.model.WrongQuestion;
import com.example.quiz.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;

@Service
public class QuestionServiceImpl implements QuestionService {

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private AnswerRecordMapper answerRecordMapper;

    @Autowired
    private WrongQuestionMapper wrongQuestionMapper;

    @Override
    public int add(Question question) {
        return questionMapper.insert(question);
    }

    @Override
    @Transactional
    public int deleteById(Long id) {
        // 先删除相关的错题记录
        wrongQuestionMapper.deleteByQuestionId(id);
        // 再删除相关的答题记录
        answerRecordMapper.deleteByQuestionId(id);
        // 最后删除题目
        return questionMapper.deleteById(id);
    }

    @Override
    public int update(Question question) {
        return questionMapper.update(question);
    }

    @Override
    @Transactional(readOnly = true)
    public Question getById(Long id) {
        return questionMapper.selectById(id);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Question> getAll() {
        return questionMapper.selectAll();
    }

    @Override
    @Transactional(readOnly = true)
    public List<Question> getPagedQuestions(int page, int size, Long categoryId, Integer difficulty) {
        int offset = (page - 1) * size;
        return questionMapper.selectPagedQuestions(offset, size, categoryId, difficulty);
    }

    @Override
    @Transactional(readOnly = true)
    public int getTotalCount(Long categoryId, Integer difficulty) {
        return questionMapper.selectTotalCount(categoryId, difficulty);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Question> getByCategoryId(Long categoryId) {
        return questionMapper.selectByCategoryId(categoryId);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Question> getRandomQuestions(int limit) {
        return questionMapper.selectRandom(limit);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Question> getByDifficulty(Integer difficultyLevel) {
        return questionMapper.selectByDifficulty(difficultyLevel);
    }

    @Override
    @Transactional(readOnly = true)
    public boolean checkAnswer(Long questionId, String answer) {
        Question question = getById(questionId);
        return question != null && question.getAnswer().equalsIgnoreCase(answer);
    }

    @Override
    @Transactional
    public void recordAnswer(Long userId, Long questionId, String answer, boolean isCorrect) {
        // 添加答题记录
        answerRecordMapper.insert(new AnswerRecord() {
            {
                setUserId(userId);
                setQuestionId(questionId);
                setAnswer(answer);
                setCorrect(isCorrect);
            }
        });

        // 如果答错了，检查是否已存在错题记录
        if (!isCorrect) {
            WrongQuestion existingWrong = wrongQuestionMapper.selectByUserAndQuestion(userId, questionId);
            if (existingWrong == null) {
                // 如果不存在，则添加到错题本
                WrongQuestion wrongQuestion = new WrongQuestion();
                wrongQuestion.setUserId(userId);
                wrongQuestion.setQuestionId(questionId);
                wrongQuestionMapper.insert(wrongQuestion);
            } else {
                // 如果已存在，则更新时间
                wrongQuestionMapper.updateCreatedAt(existingWrong.getId());
            }
        } else {
            // 如果答对了，从错题本中移除
            wrongQuestionMapper.deleteByUserAndQuestion(userId, questionId);
        }
    }

    @Override
    @Transactional(readOnly = true)
    public List<Question> getWrongQuestions(Long userId) {
        // 从错题本中获取题目ID列表
        List<WrongQuestion> wrongQuestions = wrongQuestionMapper.selectByUserId(userId);
        if (wrongQuestions.isEmpty()) {
            return new ArrayList<>();
        }

        // 获取题目详情
        List<Long> questionIds = wrongQuestions.stream()
                .map(WrongQuestion::getQuestionId)
                .collect(Collectors.toList());
        return questionMapper.selectByIds(questionIds);
    }
}
